package servlet;

import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/createBlog")
public class CreateBlog extends HttpServlet {
    // 约定 post /createBlog
    // 格式 x-www-form-urlencoded

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取请求并解析
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || title.length() == 0 || content == null || content.length() == 0){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("标题或者正文为空，无法创建博客！");
            return;
        }
        // 2. 获取会话
        HttpSession session = req.getSession(false);
        if(session == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前用户未登录！");
            return;
        }
        // 3. 获取用户信息
        User user = (User) session.getAttribute("user");
        if(user == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前用户未登录！");
            return;
        }
        int userId = user.getUserID();
        // 4. 构建 blog 对象
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(userId);
        // 5. 将 blog 插入数据库
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        // 6. 返回响应 - 重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
